<template>
  <div class="grading-page">
    <div class="header">
      <span type="text">{{ homeworkName }}</span>
    </div>
    <div class="content">
      <div class="student-info">
        <span>学号：</span>
        <span>{{ studentId }}</span>
        <span style="margin-left: 100px;">姓名：</span>
        <span>{{ studentName }}</span>
      </div>
      <div class="assignment-content">
        <span>内容：</span>        
        <textarea 
            rows="5" 
            cols="60"
            v-model="context"
            readonly>
        </textarea>
      </div>
      <!-- <div class="attachment">
       <span>上传附件</span>
        <el-upload
                ref="upload"
                :action="uploadUrl"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
                :on-remove="handleRemove"
                :file-list="fileList"
                multiple
                :show-file-list="true"
                :response-type="'json'">
          <div class="button-group"> 
           
            <el-button size="middle" style="background:rgba(228, 228, 228, 1); color: black; font-size: 22px; border-color: rgba(0, 0, 0, 0.4);">
              <i class="iconfont icon-fujiantubiao"></i>上传附件
            </el-button> 
            
            <el-button 
              size="middle" 
              style="background:rgba(228, 228, 228, 1); color: black; font-size: 22px; border-color: rgba(0, 0, 0, 0.4);"
              @click="downloadFile">
              <i class="iconfont icon-a-u6801"></i>下载
            </el-button>
            <el-button size="middle" style="background:rgba(228, 228, 228, 1); color: black; font-size: 22px; border-color: rgba(0, 0, 0, 0.4);">
              <i class="iconfont icon-shujuyulantubiao-x"></i>预览
            </el-button> 
        </div>
        </el-upload>
         
       
      </div> -->
      <div class="grade">
        <span>评分：</span>
        <br>
        <input 
          type="number" 
          v-model="finishData.score" 
          placeholder="100" />
      </div>
      <div class="rating">
        <span>请选择评分：</span>
        <el-rate v-model="value" show-text></el-rate>
      </div>
      <div class="comment">
        <span>评语：</span>
        <textarea 
          rows="5" 
          cols="60"
          v-model="finishData.comment"
          placeholder="请输入评语">
        </textarea>
      </div>
      <div class="buttons">
        <el-button @click="submitGrade">确认</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </div>
  </div>


</template>


<script>
import axios from 'axios';
export default {
  name: 'GradingPage',
  data(){
    return {
      studentId: '',
      studentName: '',
      context: '',
      finishId: '',
      value: 0,
      uploadedFiles: [],
      homeworkContent: '',
      homeworkName: '',
      homeworkId: '',
      finishData: {
        finishId: '',
        score: '',
        comment: '',
        studentId: '',
        studentName: '',
        homeworkId: '',
        state: ''
      },
      uploadUrl: 'http://localhost:9999/file/upload',
      fileList: []
    }
  },
  methods:{
    // 获取学生作业信息
    async getStudentHomework() {
      try {
        const res = await axios.get('http://localhost:9999/finish/getFinishId', {
          params: {
            finishId: this.finishId
          }
        });
        
        if(res.data && res.data.length > 0) {
          const data = res.data[0];
          this.context = data.context;
          console.log('获取到的数据:', data);
          
          // 更新数据
          this.studentId = data.studentId;
          this.studentName = data.studentName;
          this.homeworkId = data.homeworkId;
          
          if(data.comment) {
            this.homeworkContent = data.comment;
          }
          
          // 同时更新 finishData
          this.finishData = {
            finishId: this.finishId,
            score: data.score || '',
            comment: data.comment || '',
            studentId: data.studentId,
            studentName: data.studentName,
            homeworkId: data.homeworkId,
            state: data.state
          };
          
          // 获取作业名称
          await this.getHomeworkName();
        }
      } catch (error) {
        console.error('错误详情:', error);
        this.$message.error('获取作业信息失败');
      }
    },

    // 获取作业名称
    async getHomeworkName() {
      try {
        const res = await axios.get('http://localhost:9999/homework/getHomeworkId', {
          params: {
            homeworkId: this.homeworkId
          }
        });
        
        if(res.data && res.data.length > 0) {
          const homework = res.data[0];
          this.homeworkName = homework.homeworkName || '作业详情';
        }
      } catch (error) {
        console.error('获取作业名称失败:', error);
        this.homeworkName = '作业详情';
      }
    },
    
    handleUploadSuccess(response, file, fileList) {
      console.log('上传响应:', response);
      console.log('文件信息:', file);
      console.log('文件列表:', fileList);
      
      if (response) {
        this.$message.success('文件上传成功');
        this.uploadedFiles.push({
          name: file.name,
          url: response,
          flag: response,
          originalName: file.name
        });
        this.fileList = fileList;
      } else {
        this.$message.error('文件上传失败');
      }
    },

    handleUploadError(err) {
      console.error('上传失败:', err);
      this.$message.error('文件上���失败');
    },

    beforeUpload(file) {
      // 支持的文件类型
      const allowedTypes = [
        'application/msword', // .doc
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
        'application/pdf' // .pdf
      ];
      
      if (!allowedTypes.includes(file.type)) {
        this.$message.error('只能上传 Word 或 PDF 文件!');
        return false;
      }
      
      // 可以在这里添加文件大小限制
      const maxSize = 10 * 1024 * 1024; // 10MB
      if (file.size > maxSize) {
        this.$message.error('文件大小不能超过10MB!');
        return false;
      }
      
      return true;
    },

    handleRemove(file, fileList) {
      this.fileList = fileList;
    },

    async submitGrade() {
      try {
        if (!this.finishData.finishId) {
          this.$message.error('缺少必要的作业信息');
          return;
        }

        const response = await axios.post('http://localhost:9999/finish/updateFinish', 
          this.finishData
        );

        if (response.data === true) {
          this.$message.success('提交成功');
          this.$router.go(-1);
        } else {
          this.$message.error('提交失败');
        }
      } catch (error) {
        console.error('提交失败:', error);
        this.$message.error('提交失败: ' + error.message);
      }
    },

    cancel() {
      this.$router.go(-1);
    },

    // 修改下载文件的方法
    downloadFile() {
      if (this.fileList.length === 0) {
        this.$message.warning('没有可下载的文件');
        return;
      }

      const file = this.fileList[0];
      console.log('准备下载的文件信息:', file);
      console.log('文件标识:', file.response);

      if (!file.response) {
        this.$message.error('文件信息不完整');
        return;
      }

      // 使用axios下载文件
      axios({
        url: `http://localhost:9999/file/${file.response}`,
        method: 'GET',
        responseType: 'blob',
        withCredentials: true,
        headers: {
          'Access-Control-Allow-Origin': '*'
        }
      }).then(response => {
        // 创建blob链接
        const blob = new Blob([response.data]);
        const downloadUrl = window.URL.createObjectURL(blob);
        
        // 创建一个a标签用于下载
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = file.name;
        document.body.appendChild(link);
        link.click();
        
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
        
        this.$message.success('文件下载成功');
      }).catch(error => {
        console.error('下载失败:', error);
        this.$message.error('文件下载失败');
      });
    },

    // 如果需要处理多文件，可以保留这个方法
    downloadSingleFile(file) {
      if (!file.response) {
        this.$message.error('文件信息不完整');
        return;
      }

      axios({
        url: `http://localhost:9999/file/${file.response}`,
        method: 'GET',
        responseType: 'blob'
      }).then(response => {
        const blob = new Blob([response.data]);
        const downloadUrl = window.URL.createObjectURL(blob);
        
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = file.name;
        document.body.appendChild(link);
        link.click();
        
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
        
        this.$message.success('文件下载成功');
      }).catch(error => {
        console.error('下载失败:', error);
        this.$message.error('文件下载失败');
      });
    }
  },
  created() {
    // 从路由获取finishId
    this.finishId = this.$route.query.finishId;
    if (this.finishId) {
      this.getStudentHomework();
      // ���加延时检查
      setTimeout(() => {
        console.log('延时检查数据:', {
          studentId: this.studentId,
          studentName: this.studentName
        });
      }, 1000);
    }
  }
};


</script>



<style lang="less" scoped>
.grading-page {
  background-color: white;
  width: 1300px;
  min-height: 800px;
  margin: 100px auto;
  position: relative;
  display: flex;
  flex-direction: column;

  .header {
    margin: 20px 20px;
    border: 1px solid #ccc;
    width: 250px;
    height: 57px;
    font-size: 24px;
    font-family: "楷体";
    box-shadow: 0 0px 20px rgba(0, 0, 0, 0.4);
    background: rgba(149, 216, 230, 1);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .content {
    font-size: 20px;
    font-family: "楷体";
    margin: 20px 20px;

    .student-info {
      label {
        font-weight: bold;
      }
    }

    .assignment-content {
      margin-bottom: 20px;
      textarea {
        width: 95%;
        height: 100px;
        border: 1px solid #ccc;
        padding: 10px;
        resize: none;
      }
    }

    .attachment {
      margin-bottom: 20px;
      .button-group {
        display: flex;
        gap: 20px; /* 设置按钮之间的间距 */
        align-items: center;
        
        margin-top: 10px; /* 根据需要调整 */
      }
      .el-button {
        flex-grow: 1; /* 如果你希望按钮填满可用空间 */
      }
    }

    .grade {
      margin-bottom: 20px;
      input[type="number"] {
        width: 50px;
        border: 1px solid #ccc;
        padding: 5px;
      }
    }

    .rating {
      margin-bottom: 20px;
    }

    .comment {
      margin-bottom: 20px;
      textarea {
        width: 95%;
        height: 100px;
        border: 1px solid #ccc;
        padding: 10px;
        resize: none;
      }
    }

    .buttons {
      text-align: center;
      margin-top: 20px;
      .el-button {
        margin: 0 10px;
      }
    }
  }
}


</style>